<template>
  <div class="playlist-management">
    <div class="header">
      <h2>播放列表管理</h2>
      <el-button type="primary" @click="showCreateDialog">新增播放列表</el-button>
    </div>

    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="播放列表名称">
          <el-input v-model="searchForm.name" placeholder="请输入播放列表名称"></el-input>
        </el-form-item>
        <el-form-item label="创建者">
          <el-input v-model="searchForm.creatorName" placeholder="请输入创建者名称"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态">
            <el-option label="全部" value=""></el-option>
            <el-option label="启用" :value="1"></el-option>
            <el-option label="禁用" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否推荐">
          <el-select v-model="searchForm.isRecommended" placeholder="请选择">
            <el-option label="全部" value=""></el-option>
            <el-option label="是" :value="true"></el-option>
            <el-option label="否" :value="false"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table
        :data="playlistList"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
        v-loading="loading"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="playlistId" label="列表ID" width="100"></el-table-column>
      <el-table-column prop="name" label="列表名称" width="180"></el-table-column>
      <el-table-column label="创建者" width="180">
        <template #default="{ row }">
          <div v-if="row.creator">
            {{ row.creator.nickname }} (ID: {{ row.creator.userId }})
          </div>
        </template>
      </el-table-column>
      <el-table-column label="封面" width="120">
        <template #default="{ row }">
          <el-image
              style="width: 80px; height: 80px"
              :src="row.coverUrl"
              :preview-src-list="[row.coverUrl]"
              fit="cover"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="tags" label="标签" width="150"></el-table-column>
      <el-table-column prop="songCount" label="歌曲数" width="80"></el-table-column>
      <el-table-column prop="playCount" label="播放量" width="100"></el-table-column>
      <el-table-column prop="isPublic" label="公开状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.isPublic ? 'success' : 'info'">
            {{ row.isPublic ? '公开' : '私有' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否推荐" width="100">
        <template #default="{ row }">
          <el-switch
              v-model="row.isRecommended"
              :active-value="true"
              :inactive-value="false"
              @change="toggleRecommended(row.playlistId, row.isRecommended)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="showEditDialog(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deletePlaylist(row.playlistId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
      ></el-pagination>
    </div>

    <!-- 新增/编辑播放列表对话框 -->
    <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="50%"
        @closed="resetForm"
    >
      <el-form
          :model="playlistForm"
          :rules="rules"
          ref="playlistFormRef"
          label-width="100px"
      >
        <el-form-item label="列表名称" prop="name">
          <el-input v-model="playlistForm.name"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="playlistForm.description"></el-input>
        </el-form-item>
        <el-form-item label="封面URL" prop="coverUrl">
          <el-input v-model="playlistForm.coverUrl"></el-input>
          <el-upload
              class="avatar-uploader"
              action=""
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :http-request="uploadCover"
          >
            <el-button type="primary">上传封面</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-input v-model="playlistForm.tags" placeholder="多个标签用逗号分隔"></el-input>
        </el-form-item>
        <el-form-item label="公开状态" prop="isPublic">
          <el-switch
              v-model="playlistForm.isPublic"
              :active-value="true"
              :inactive-value="false"
          ></el-switch>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
              v-model="playlistForm.status"
              :active-value="1"
              :inactive-value="0"
          ></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '../services/api'

export default {
  name: 'PlaylistManagement',
  setup() {
    const playlistList = ref([])
    const selectedPlaylists = ref([])
    const loading = ref(false)
    const dialogVisible = ref(false)
    const dialogTitle = ref('新增播放列表')
    const playlistFormRef = ref(null)
    const isEditMode = ref(false)
    const currentPlaylistId = ref(null)

    const searchForm = reactive({
      name: '',
      creatorName: '',
      status: '',
      isRecommended: ''
    })

    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })

    const playlistForm = reactive({
      name: '',
      description: '',
      coverUrl: '',
      tags: '',
      isPublic: true,
      status: 1
    })

    const rules = {
      name: [
        { required: true, message: '请输入播放列表名称', trigger: 'blur' }
      ],
      description: [
        { required: true, message: '请输入播放列表描述', trigger: 'blur' }
      ],
      coverUrl: [
        { required: true, message: '请输入封面URL', trigger: 'blur' }
      ]
    }

    // 获取播放列表
    const fetchPlaylistList = async () => {
      try {
        loading.value = true
        const params = {
          page: pagination.currentPage,
          size: pagination.pageSize,
          name: searchForm.name,
          creatorName: searchForm.creatorName,
          status: searchForm.status,
          isRecommended: searchForm.isRecommended
        }

        const response = await api.contentManageApi.getPlaylistManageList(params)
        if (response.code === 200) {
          playlistList.value = response.data.list
          pagination.total = response.data.total
        } else {
          ElMessage.error(response.message || '获取播放列表失败')
        }
      } catch (error) {
        ElMessage.error('请求出错：' + error.message)
      } finally {
        loading.value = false
      }
    }

    // 搜索
    const handleSearch = () => {
      pagination.currentPage = 1
      fetchPlaylistList()
    }

    // 重置搜索
    const resetSearch = () => {
      searchForm.name = ''
      searchForm.creatorName = ''
      searchForm.status = ''
      searchForm.isRecommended = ''
      handleSearch()
    }

    // 分页大小改变
    const handleSizeChange = (val) => {
      pagination.pageSize = val
      fetchPlaylistList()
    }

    // 当前页改变
    const handleCurrentChange = (val) => {
      pagination.currentPage = val
      fetchPlaylistList()
    }

    // 表格选择项变化
    const handleSelectionChange = (selection) => {
      selectedPlaylists.value = selection.map(item => item.playlistId)
    }

    // 显示新增对话框
    const showCreateDialog = () => {
      dialogTitle.value = '新增播放列表'
      isEditMode.value = false
      dialogVisible.value = true
    }

    // 显示编辑对话框
    const showEditDialog = (row) => {
      dialogTitle.value = '编辑播放列表'
      isEditMode.value = true
      currentPlaylistId.value = row.playlistId

      // 填充表单数据
      Object.keys(playlistForm).forEach(key => {
        playlistForm[key] = row[key]
      })

      dialogVisible.value = true
    }

    // 重置表单
    const resetForm = () => {
      if (playlistFormRef.value) {
        playlistFormRef.value.resetFields()
      }
      Object.assign(playlistForm, {
        name: '',
        description: '',
        coverUrl: '',
        tags: '',
        isPublic: true,
        status: 1
      })
      currentPlaylistId.value = null
      isEditMode.value = false
    }

    // 提交表单
    const submitForm = async () => {
      try {
        await playlistFormRef.value.validate()

        if (isEditMode.value) {
          // 更新播放列表
          await api.playlistApi.updatePlaylist(currentPlaylistId.value, playlistForm)
          ElMessage.success('播放列表更新成功')
        } else {
          // 创建播放列表
          await api.playlistApi.createPlaylist(playlistForm)
          ElMessage.success('播放列表创建成功')
        }

        dialogVisible.value = false
        fetchPlaylistList()
      } catch (error) {
        if (error.name !== 'ValidateError') {
          ElMessage.error('操作失败：' + (error.message || '未知错误'))
        }
      }
    }

    // 删除播放列表
    const deletePlaylist = (playlistId) => {
      ElMessageBox.confirm('确定要删除该播放列表吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await api.contentManageApi.deleteAdminPlaylist(playlistId)
          ElMessage.success('删除成功')
          fetchPlaylistList()
        } catch (error) {
          ElMessage.error('删除失败：' + error.message)
        }
      }).catch(() => {})
    }

    // 切换推荐状态
    const toggleRecommended = async (playlistId, isRecommended) => {
      try {
        await api.contentManageApi.setPlaylistRecommended(playlistId, isRecommended)
        ElMessage.success('推荐状态更新成功')
      } catch (error) {
        ElMessage.error('更新推荐状态失败：' + error.message)
        // 回滚状态
        const playlist = playlistList.value.find(p => p.playlistId === playlistId)
        if (playlist) {
          playlist.isRecommended = !isRecommended
        }
      }
    }

    // 上传封面
    const beforeAvatarUpload = (file) => {
      const isImage = file.type.startsWith('image/')
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isImage) {
        ElMessage.error('上传文件必须是图片格式!')
      }
      if (!isLt5M) {
        ElMessage.error('上传图片大小不能超过 5MB!')
      }

      return isImage && isLt5M
    }

    const uploadCover = async (options) => {
      try {
        const formData = new FormData()
        formData.append('file', options.file)
        formData.append('type', 'cover')

        const response = await api.fileApi.uploadFile(formData)
        if (response.code === 200) {
          playlistForm.coverUrl = response.data.url
          ElMessage.success('上传成功')
        } else {
          ElMessage.error(response.message || '上传失败')
        }
      } catch (error) {
        ElMessage.error('上传出错：' + error.message)
      }
    }

    // 初始化
    onMounted(() => {
      fetchPlaylistList()
    })

    return {
      playlistList,
      selectedPlaylists,
      loading,
      dialogVisible,
      dialogTitle,
      playlistFormRef,
      searchForm,
      pagination,
      playlistForm,
      rules,
      handleSearch,
      resetSearch,
      handleSizeChange,
      handleCurrentChange,
      handleSelectionChange,
      showCreateDialog,
      showEditDialog,
      resetForm,
      submitForm,
      deletePlaylist,
      toggleRecommended,
      beforeAvatarUpload,
      uploadCover
    }
  }
}
</script>

<style scoped>
.playlist-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-bar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.avatar-uploader {
  margin-top: 10px;
}
</style>